package proyecto.domain;

import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;

@RequestMapping("/documentoes")
@Controller
@RooWebScaffold(path = "documentoes", formBackingObject = Documento.class)
@RooWebFinder
public class DocumentoController {

    @RequestMapping(value = "/{id}/image", method = RequestMethod.GET)
    public String showImage(@PathVariable("id") Long id, HttpServletResponse response, Model model) {
        Documento documento = Documento.findDocumento(id);
        if (documento != null) {
            byte[] image = documento.getImage();
            if (image != null) {
                try {
                    response.setContentType(documento.getContentType());
                    OutputStream out = response.getOutputStream();
                    IOUtils.copy(new ByteArrayInputStream(image), out);
                    out.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Documento documento, BindingResult bindingResult, Model uiModel, @RequestParam("image") MultipartFile multipartFile, HttpServletRequest httpServletRequest) {

        SecurityContext securityContext = SecurityContextHolder.getContext();
    	String usu = securityContext.getAuthentication().getName();

    	
    	
    	if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, documento);
            return "documentoes/create";
        }
        uiModel.asMap().clear();
        documento.setContentType(multipartFile.getContentType());
        if(multipartFile.getContentType().contentEquals("image/jpeg") || multipartFile.getContentType().contentEquals("application/pdf")){
        documento.persist();
        return "redirect:/documentoes/" + encodeUrlPathSegment(documento.getId().toString(), httpServletRequest);
        }else{
        	return "redirect:/";
        }

        /*
    	
    	String usu = securityContext.getAuthentication().getName();
    	
    	@Autowired
    	//System.out.println("el usuario es: "+usu);
    	
    	
    Usuario ho = Usuario.findUsuariosByNombre1(usu).getSingleResult();

    Long id = ho.getId();
    Integer version = ho.getVersion();

    //System.out.println("el id del user es: "+ho.getId()+ " La version es: "+ ho.getVersion());

        */

    }
   /*
    @RequestMapping(params = "form", produces = "text/html")
    public String createForm1(Model uiModel) {
        populateEditForm(uiModel, new Documento());
        SecurityContext securityContext = SecurityContextHolder.getContext();
        String uu = securityContext.getAuthentication().getName();
        Usuario usuuuu = Usuario.findUsuariosByUsernameEquals(uu).getSingleResult();
        uiModel.addAttribute("usxdoc", Usuario.findUsuario(usuuuu.getId()));
        
        return "documentoes/create";
    }
   */
    /*
    @RequestMapping(params= "form", produces = "text/html")
    public String createForm1(Model uiModel) {
       String username = SecurityContextHolder.getContext().getAuthentication().getName();
       List<Usuario> usuarioList = Usuario.findUsuariosByUsernameEquals(username).getResultList();
       if(!usuarioList.isEmpty()) {
          Usuario user = usuarioList.get(0);
          List<Documento> resultList = Documento.findDocumentoesByPropietario(user).getResultList();
          uiModel.addAttribute("documentoes",resultList);
       }
       addDateTimeFormatPatterns(uiModel);
       return "documentoes/list";
    }
    
    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Documento documento, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, documento);
            return "documentoes/create";
        }
             
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        List<Usuario> usuarioList = Usuario.findUsuariosByUsernameEquals(username).getResultList();
        if(!usuarioList.isEmpty()) {
            Usuario user = usuarioList.get(0);
            usuario.setUsuario(user);
        }
        uiModel.asMap().clear();
        documento.persist();
        return "redirect:/documentoes/" + encodeUrlPathSegment(docum.getId().toString(), httpServletRequest);
    }
    */
    
    /*
    @RequestMapping(varalue="/login", method = RequestMethod.GET)
    public String printUser(Model uiModel) {
    	SecurityContext securityContext = SecurityContextHolder.getContext();
    	String uu = securityContext.getAuthentication().getName();
        Usuario usuuuu = Usuario.findUsuariosByNombre(uu).getSingleResult();
        uiModel.addAttribute("usxdoc", Usuario.findUsuario(usuuuu.getId()));
   
        
        return "hello";
   
    }
    */
    /*
    SecurityContext securityContext = SecurityContextHolder.getContext();
	
	String usu = securityContext.getAuthentication().getName();
	
	@Autowired
	//System.out.println("el usuario es: "+usu);
	
	
Usuario ho = Usuario.findUsuariosByNombre1(usu).getSingleResult();

Long id = ho.getId();
Integer version = ho.getVersion();

//System.out.println("el id del user es: "+ho.getId()+ " La version es: "+ ho.getVersion());

    */
    
    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws ServletException {
        binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
    }
 @RequestMapping(value = "/update", method = RequestMethod.POST, produces = "text/html")
    
    public String update(@Valid Documento documento, BindingResult bindingResult, Model uiModel, @RequestParam("image") MultipartFile multipartFile, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, documento);
            return "documentoes/update";
        }
        uiModel.asMap().clear();
        
        
       documento.setContentType(multipartFile.getContentType());
       System.out.println("EL CONTENT TYPE ES: "+documento.getContentType());
        
        documento.merge();
        return "redirect:/documentoes/" + encodeUrlPathSegment(documento.getId().toString(), httpServletRequest);
    }
    
}
